<?php
// +----------------------------------------------------------------------
// | 中间件 - 路由TOKEN解析
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace app\middleware;

use app\model\SystemUsersModel;
use app\service\JwtTokenService;
use app\Request;

class RouteTokenParse
{
    /**
     * 处理请求
     *
     * @param Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取请求的jwt字符串
        $jwt = str_replace('Bearer ', '', $request->header('Authorization', ''));
        if ($jwt) {
            // 解析jwt
            $token = JwtTokenService::parseToken($jwt);
        }
        if (!empty($token)) {
            $user = SystemUsersModel::queryOrder()->find($token['uid']);
            // 将用户信息写入请求
            $request->setUser($user);
        }
        return $next($request);
    }
}
